//
//  Marker
//
//  Created by Ryan Mark on 2008-08-15.
//  Copyright (c) 2008 Ryan Mark. All rights reserved.
//
import com.modestmaps.Map;
import com.modestmaps.core.*;
import com.ryanmark.*;
import flash.geom.Point;
import mx.transitions.easing.*;
import mx.transitions.Tween;
import flash.filters.BlurFilter;
import flash.display.BitmapData;

class com.ryanmark.MarkerManager 
extends Object 
{
  private var __marker_obj:Object;
  
  private var __timeline_mc:MovieClip;
  private var __timeLineMarkerSymbol_str:String;
  private var __timeLineMarker_mc:MovieClip;
  
  private var __modestMaps_mc:MovieClip;
  private var __mapMarkerSymbol_str:String;
  private var __mapMarker_mc:MovieClip;
  
  private var __contentPaneSymbol_str:String;
  private var __contentPane_mc:MovieClip;
  
  private var __captionFmt:TextFormat;
  
  private static var __monthNames_array:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
  
  public var id:String;
  
	function MarkerManager(pMarker:Object,pContentPaneSymbol:String,pTimeLine:MovieClip,
	  pTimeLineMarkerSymbol:String,pModestMaps:MovieClip,pMapMarkerSymbol:String)
	{
		__marker_obj=pMarker;
		this.id = __marker_obj.id;
		__timeline_mc=pTimeLine;
		__timeLineMarkerSymbol_str=pTimeLineMarkerSymbol;
    
    __modestMaps_mc=pModestMaps;
    __mapMarkerSymbol_str=pTimeLineMarkerSymbol;
		
		__contentPaneSymbol_str=pContentPaneSymbol;
    
    //__contentPane_mc = new ContentPane(__marker_obj.id,__marker_obj.date,__marker_obj.hed,__marker_obj.deck,__marker_obj.text);
    
    __mapMarker_mc = __modestMaps_mc.putMarker(__marker_obj.id,pMarker.location,__mapMarkerSymbol_str);
    __mapMarker_mc.manager=this;
    
    __timeLineMarker_mc = __timeline_mc.addPushPin(__marker_obj.id,pMarker.date,__timeLineMarkerSymbol_str);
    __timeLineMarker_mc.manager=this;
    
    //styles
    __captionFmt = new TextFormat();
    __captionFmt.color = 0x7a7a7a;
    __captionFmt.font = "Arial";
    __captionFmt.kerning = true;
    __captionFmt.size = 10;
    __captionFmt.letterSpacing = -1;
	  
	}
	
	function onClick():Void {
	  var oldId = _level0.content_pane.manager.id;
	  //clear old content pane and attach new one (only if its a new pane)
	  if(oldId != this.id){
  	  //var myTween:Tween = new Tween(_level0.content_pane, "_x", Strong.easeOut, contentPaneX, _root.mapWidth_num, 3, true);
	    _level0.content_pane.removeMovieClip();
	    __contentPane_mc = _level0.attachMovie(__contentPaneSymbol_str,"content_pane",1000);
  	  __contentPane_mc.manager=this;
	  }
	    
	  //position the pane
	  var contentPaneY = (_root.mapHeight_num - __contentPane_mc._height) / 2;
	  __contentPane_mc._y = contentPaneY;
	  var contentPaneX = _root.mapWidth_num - __contentPane_mc._width - contentPaneY;
	  __contentPane_mc._x = contentPaneX;
	    
	  //don't need to do this if the right content is already on the screen
	  if(oldId != this.id){
	    //some glitz
	    //new Tween(__contentPane_mc, "_alpha", Strong.easeOut, 0, 100, 30, false);
      new Tween(__contentPane_mc, "_x", Strong.easeOut, _root.mapWidth_num, contentPaneX, 30, false);
      /*var myTween:Tween = new Tween(__contentPane_mc, "blur", Strong.easeOut, 20, 0, 3, true);
          myTween.onMotionChanged = function() {
              _level0.content_pane.filters = [new BlurFilter(_level0.content_pane.blur, 0, 1)];
          };*/
      
      //extract the text format from the fields - (actionscript cant copy objects. lame.)
	    var tmpYrTxtFmt = __contentPane_mc.year_txt.getTextFormat();
	    var yrTxtFmt = new TextFormat();
	    for (var key in tmpYrTxtFmt) {
	      yrTxtFmt[key] = tmpYrTxtFmt[key];
	    }
	    var tmpDtTxtFmt = __contentPane_mc.date_txt.getTextFormat();
	    var dtTxtFmt = new TextFormat();
	    for (var key in tmpDtTxtFmt) {
	      dtTxtFmt[key] = tmpDtTxtFmt[key];
	    }
	    var tmpHedTxtFmt = __contentPane_mc.hed_txt.getTextFormat();
	    var hedTxtFmt = new TextFormat();
	    for (var key in tmpHedTxtFmt) {
	      hedTxtFmt[key] = tmpHedTxtFmt[key];
	    }
	    var tmpDeckTxtFmt = __contentPane_mc.deck_txt.getTextFormat();
	    var deckTxtFmt = new TextFormat();
	    for (var key in tmpDeckTxtFmt) {
	      deckTxtFmt[key] = tmpDeckTxtFmt[key];
	    }
	    var tmpBodyTxtFmt = __contentPane_mc.body_txt.getTextFormat();
	    var bodyTxtFmt = new TextFormat();
	    for (var key in tmpBodyTxtFmt) {
	      bodyTxtFmt[key] = tmpBodyTxtFmt[key];
	    }
	    
	    //populate the content pane
	    __contentPane_mc.year_txt.text = __marker_obj.date.getFullYear();
	    __contentPane_mc.year_txt.setTextFormat(yrTxtFmt);
	    __contentPane_mc.date_txt.text = __monthNames_array[__marker_obj.date.getMonth()]+" "+__marker_obj.date.getDate();
	    __contentPane_mc.date_txt.setTextFormat(dtTxtFmt);
	    __contentPane_mc.hed_txt.text = __marker_obj.hed;
	    __contentPane_mc.hed_txt.setTextFormat(hedTxtFmt);
	    __contentPane_mc.deck_txt.text = __marker_obj.deck;
	    __contentPane_mc.deck_txt.setTextFormat(deckTxtFmt);
	    __contentPane_mc.body_txt.text = __marker_obj.body;
	    __contentPane_mc.body_txt.setTextFormat(bodyTxtFmt);
	    __contentPane_mc.close_btn.onRelease = function() {
	      _level0.content_pane.manager.closeContentPane();
	    };
	    
	    // OK we have to add the media now
	    var loaders=new Array();
	    __contentPane_mc.insideHeight=0;
	    __contentPane_mc.mediaContainer_mc.width=__contentPane_mc.mediaContainer_mc._width;
	    
	    //create the MovieClip Loader Listener
	    var mclListener = {
        onLoadInit: function(target_mc:MovieClip) {
          var scale = (target_mc._parent._parent.width/target_mc._width)*100;
          target_mc._xscale = scale;
          target_mc._yscale = scale;
          var tmpMC = target_mc._parent;
          tmpMC.createTextField('caption_'+i+"_txt", tmpMC.getNextHighestDepth(),0,target_mc._height+3,100,100);
          tmpMC['caption_'+i+"_txt"].autoSize = true;
          tmpMC['caption_'+i+"_txt"].text = tmpMC.manager.markerObject.media[tmpMC.mediaId].caption;
          tmpMC['caption_'+i+"_txt"].wordWrap = true;
          tmpMC['caption_'+i+"_txt"].setTextFormat(tmpMC.manager.captionFormat);
          _root.content_pane.insideHeight += target_mc._parent._height;
        }
      }
	    
	    for ( var i in __marker_obj.media ) {
	      if (i>2) break;
	      if ( __marker_obj.media[i].type == "youtube" ) {
	        var loaderNum = loaders.push(new MovieClipLoader())-1;
	        var tmpMC = __contentPane_mc.mediaContainer_mc.createEmptyMovieClip( "media_"+i+"_mc", 
	                      __contentPane_mc.mediaContainer_mc.getNextHighestDepth());
	        tmpMC.thumb_mc = tmpMC.createEmptyMovieClip( "thumb_mc", tmpMC.getNextHighestDepth());
	        tmpMC._y=i*150;
	        
          loaders[loaderNum].addListener(mclListener);
          // load the player
          loaders[loaderNum].loadClip("http://img.youtube.com/vi/"+__marker_obj.media[i].videoid+"/2.jpg", tmpMC.thumb_mc);
          
          tmpMC.manager=this;
          tmpMC.mediaId=i;
          
          tmpMC.onRelease = function() {this.manager.playYouTubeMedia(this.mediaId);};
          
	      } else if (__marker_obj.media[i].type == "image") {
	        var loaderNum = loaders.push(new MovieClipLoader())-1;
	        tmpMC = __contentPane_mc.mediaContainer_mc.createEmptyMovieClip( "media_"+i+"_mc", 
	                      __contentPane_mc.mediaContainer_mc.getNextHighestDepth());
	        tmpMC.thumb_mc = tmpMC.createEmptyMovieClip( "thumb_mc", tmpMC.getNextHighestDepth());
	        tmpMC._y=i*150;
	        
          loaders[loaderNum].addListener(mclListener);
          
          // load the image
          loaders[loaderNum].loadClip(__marker_obj.media[i].url, tmpMC.thumb_mc);
          
          tmpMC.manager=this;
          tmpMC.mediaId=i;
          tmpMC.onRelease = function() {this.manager.openZoomImage(this.mediaId);};
	        
	      }
	    }
	    
    }
	  
	  // position the map
	  // we can get the modestmap to pan if we feed it a point with the difference of position (turned it off - buggy)
	  var newPos:Point = __modestMaps_mc.locationPoint(__marker_obj.location,__modestMaps_mc);
	  newPos.x = newPos.x + (contentPaneX/2 + (_root.mapWidth_num/2 - contentPaneX));
	  /*var curPos:Point = __modestMaps_mc.locationPoint(__modestMaps_mc.getCenterZoom()[0]);
	  var chgPos:Point = new Point( Math.round((newPos.x-curPos.x)/__modestMaps_mc.panFrames), Math.round((newPos.y-curPos.y)/__modestMaps_mc.panFrames) );
	  __modestMaps_mc.panMap(chgPos);*/
    
    //this is a hack to get the right zoom level and position with the content pane on the screen
    if(5-__modestMaps_mc.getCenterZoom()[1] == 0) {
      __modestMaps_mc.setCenterZoom(__modestMaps_mc.pointLocation(newPos,__modestMaps_mc),5);
    } else {
      __modestMaps_mc.setCenterZoom(__modestMaps_mc.pointLocation(newPos,__modestMaps_mc),5);
      newPos = __modestMaps_mc.locationPoint(__marker_obj.location,__modestMaps_mc);
  	  newPos.x = newPos.x + (contentPaneX/2 + (_root.mapWidth_num/2 - contentPaneX));
      __modestMaps_mc.setCenterZoom(__modestMaps_mc.pointLocation(newPos,__modestMaps_mc),5);
    }
    
    //position the timeline
	  __timeline_mc.moveToDate(__marker_obj.date);
	}
	
	function closeContentPane(){
	  var myTween = new Tween(__contentPane_mc, "_x", Strong.easeOut, __contentPane_mc._x, _root.mapWidth_num,  30, false);
    myTween.onMotionFinished = function() {
      _level0.content_pane.manager.cleanUpContentPane();
    };
	}
	
	function cleanUpContentPane() {
	  _level0.content_pane.removeMovieClip();
	}
	
	function playYouTubeMedia(mediaId:Number) {
	  //trace("Play Media: "+__marker_obj.media[mediaId].videoid);
	  _root.curtain = _root.createEmptyMovieClip("curtain",2000);
	  _root.curtain.beginFill(0x000000);
    _root.curtain.moveTo(0, 0);
    _root.curtain.lineTo(Stage.width, 0);
    _root.curtain.lineTo(Stage.width, Stage.height);
    _root.curtain.lineTo(0, Stage.height);
    _root.curtain.lineTo(0, 0);
    _root.curtain.endFill();
    _root.curtain._alpha=0;
    _root.curtain.manager=this;
    _root.curtain.onRelease = function() {
      this.manager.closeYouTubeMedia();
    }
    
    //glitz
    new Tween(_root.curtain, "_alpha", Strong.easeOut, 0, 40,  30, false);
    
	  // create a MovieClip to load the player into
    _root.ytplayer = _root.createEmptyMovieClip("ytplayer", 2001);
    // create a MovieClipLoader to handle the loading of the player
    _root.ytPlayerLoader = new MovieClipLoader();
    
    _root.ytPlayerLoader.addListener({
      onLoadInit: function(target_mc:MovieClip) {
        _root.loadInterval = setInterval(_root.checkPlayerLoaded, 250);
        _root.ytplayer._x = (Stage.width-425)/2;
        _root.ytplayer._y = (Stage.height-344)/2;
      }
    });
    _root.checkPlayerLoaded = function(){
      if (_root.ytplayer.isPlayerLoaded()) {
          clearInterval(_root.loadInterval);
      }
    }
    // load the player
    _root.ytPlayerLoader.loadClip("http://www.youtube.com/v/"+__marker_obj.media[mediaId].videoid+"&autoplay=1", _root.ytplayer);
	}
	
	function closeYouTubeMedia() {
	  var myTween = new Tween(_root.curtain, "_alpha", Strong.easeOut, 40, 0,  30, false);
    myTween.onMotionFinished = function() {
  	  _root.curtain.removeMovieClip();
    };
	  _root.ytplayer.destroy();
	  _root.ytplayer.removeMovieClip();
	}

	function openZoomImage(mediaId:Number) {
	  //trace("Play Media: "+__marker_obj.media[mediaId].videoid);
	  _root.curtain = _root.createEmptyMovieClip("curtain",2000);
	  _root.curtain.beginFill(0x000000);
    _root.curtain.moveTo(0, 0);
    _root.curtain.lineTo(Stage.width, 0);
    _root.curtain.lineTo(Stage.width, Stage.height);
    _root.curtain.lineTo(0, Stage.height);
    _root.curtain.lineTo(0, 0);
    _root.curtain.endFill();
    _root.curtain._alpha=0;
    _root.curtain.manager=this;
    _root.curtain.onRelease = function() {
      this.manager.closeZoomImage();
    }
    
    //glitz
    new Tween(_root.curtain, "_alpha", Strong.easeOut, 0, 40,  30, false);

    //copy the original image
    _root.zoomImage = _root.createEmptyMovieClip("zoomImage", 2001);
    
    var tmpThumb = __contentPane_mc.mediaContainer_mc["media_"+mediaId+"_mc"].thumb_mc;
    var fullWidth = tmpThumb._width/(tmpThumb._xscale/100);
    var fullHeight = tmpThumb._height/(tmpThumb._yscale/100);
    
    var bd:BitmapData = new BitmapData(fullWidth,fullHeight);
    bd.draw(__contentPane_mc.mediaContainer_mc["media_"+mediaId+"_mc"].thumb_mc);
    _root.zoomImage.attachBitmap(bd, _root.zoomImage.getNextHighestDepth());
    _root.zoomImage.cacheAsBitmap = true;
    
    //resize image (we scale it twice to make sure width and height both fit with space on the edges)
    _root.zoomImage._xscale=100;
    _root.zoomImage._yscale=100;
    var scale = 100
    if (_root.zoomImage._y > Stage.width*.75) {
      scale = ( ( (Stage.width*.75)/_root.zoomImage._height ) * (scale/100) ) *100;
      _root.zoomImage._xscale,_root.zoomImage._yscale=scale;
    }
    if (_root.zoomImage._x > Stage.width*.75) {
      scale = ( ( (Stage.width*.75)/_root.zoomImage._width ) * (scale/100) ) *100;
      _root.zoomImage._xscale,_root.zoomImage._yscale=scale;
    }
    
    //postion image
    _root.zoomImage._x = (Stage.width-_root.zoomImage._width)/2;
    _root.zoomImage._y = (Stage.height-_root.zoomImage._height)/2;
	}
	
	function closeZoomImage() {
	  var myTween = new Tween(_root.curtain, "_alpha", Strong.easeOut, 40, 0,  30, false);
    myTween.onMotionFinished = function() {
  	  _root.curtain.removeMovieClip();
    };
	  _root.zoomImage.removeMovieClip();
	}
	
	function get markerObject():Object {
	  return __marker_obj;
	}
	
	function get captionFormat():TextFormat {
	  return __captionFmt;
	}
	
}